package com.huang.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.huang.modle.MenuItem;

public class TestMain {

	public static void main(String[] args) 
	{
		String url = "http://waimai.taobao.com/shop_detail.htm?shopId=406&city=330100";
		StringBuffer html = new StringBuffer();
		try 
		{
			Document doc = Jsoup.connect(url).post();
			Elements list = doc.getElementsByClass("shopping_data");
			Elements images = doc.getElementsByClass("img-link");
			ArrayList<MenuItem> menuItems = new ArrayList<MenuItem>();
			MenuItem oneMenuItem = null;
			for (Element link : list) 
			{
				oneMenuItem = new MenuItem();
				oneMenuItem.discounted_price = Float.parseFloat(link.attr("discounted_price"));
				oneMenuItem.normal_price = Float.parseFloat(link.attr("normal_price"));
				oneMenuItem.name = link.attr("item_name");
				for(Element aTag : images)
				{
					if(aTag.attr("title").equals(oneMenuItem.name))
					{
						Element img = aTag.select("img[src]").first();
						oneMenuItem.imageUrl = img.attr("src");
						break;
					}
					
				}
				menuItems.add(oneMenuItem);
			}
			packageHtml(menuItems);
		
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	
	private static void packageHtml(ArrayList<MenuItem> menuItems)
	{
		StringBuffer html = new StringBuffer();
		html.append("<table>");
		for(MenuItem oneMenuItem : menuItems)
		{
			html.append("<tr>");
				html.append("<td>"); 
					html.append("<img border='0' "); 
						html.append("src='"); 
							html.append(oneMenuItem.imageUrl);
						html.append("'"); 
					html.append(" />"); 
				html.append("</td>");
			html.append("</tr>");
			
			
		}
		html.append("</table>");
		System.out.println(html.toString());
	}
}
